'use client'
import React, { useEffect, useState, useRef, useCallback } from 'react'
import Image from "next/image"
import { LOCAL_USER, ROUTE_LOGIN, SESSION_INFORMATION, EVENTBUS_INFROMATION_UPDATE, EVENTBUS_USER_UPDATE, ROUTE_DASHBOARD, SESSION_USERS } from '@/config/settings';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import eventBus from '@/utils/eventBus';
import { CircleUserRound } from 'lucide-react';

export default function Header() {
  const router = useRouter();
  const [userInfo, setUserInfo] = useState({});
  const [isShowPopup, setIsShowPopup] = useState(false);
  const popupRef = useRef(null);
  const [information, setInformation] = useState({});

  const fetchInformation = useCallback(() => {
    if (sessionStorage.getItem(SESSION_INFORMATION)) {
      setInformation(JSON.parse(sessionStorage.getItem(SESSION_INFORMATION)));
    } else {
      fetch('/api/contact', { method: 'GET', credentials: 'include', })
        .then(response => response.json())
        .then(data => {
          setInformation(data.data);
          sessionStorage.setItem(SESSION_INFORMATION, JSON.stringify(data.data));
        })
    }
  }, [])

  const fetchUserInfo = useCallback(() => {
    if (localStorage.getItem(LOCAL_USER)) {
      setUserInfo(JSON.parse(localStorage.getItem(LOCAL_USER)));
    } else {
      router.push(ROUTE_LOGIN);
      return;
    }
  }, [router])

  useEffect(() => {
    fetchUserInfo();
    fetchInformation();
  }, [fetchUserInfo, fetchInformation]);

  const switchPopup = () => {
    setIsShowPopup(!isShowPopup);
  }

  useEffect(() => {
    if (!isShowPopup) return;
    const handleClickOutside = (event) => {
      if (popupRef.current && !popupRef.current.contains(event.target)) {
        setIsShowPopup(false);
      }
    };
    document.addEventListener('click', handleClickOutside);
    return () => {
      document.removeEventListener('click', handleClickOutside);
    };
  }, [isShowPopup]);

  const handleLogout = async () => {
    await fetch('/api/admin/auth/logout', { method: 'GET', credentials: 'include', })
    localStorage.removeItem(LOCAL_USER);
    sessionStorage.removeItem(SESSION_INFORMATION);
    if (sessionStorage.getItem(SESSION_USERS)) { sessionStorage.removeItem(SESSION_USERS) }
    router.push(ROUTE_LOGIN);
  }

  const popupList = [
    { name: '网站信息', path: '/admin/contact', icon: '/icon-contact.svg', isTarget: false },
    { name: '修改资料', path: '/admin/settings', icon: '/icon-settings.svg', isTarget: false },
    { name: '刷新信息', path: '/admin/auth/login', icon: '/icon-refresh.svg', isTarget: false },
    { name: '前往主站', path: '/', icon: '/icon-pages.svg', isTarget: true },
    { name: '退出登录', icon: '/icon-close.svg', method: handleLogout }
  ]

  useEffect(() => {
    const handler = () => {
      fetchInformation();
    };
    eventBus.on(EVENTBUS_INFROMATION_UPDATE, handler);
    return () => {
      eventBus.off(EVENTBUS_INFROMATION_UPDATE, handler);
    };
  }, [fetchInformation]);

  useEffect(() => {
    const handler = (e) => {
      fetchUserInfo();
    };
    eventBus.on(EVENTBUS_USER_UPDATE, handler);
    return () => {
      eventBus.off(EVENTBUS_USER_UPDATE, handler);
    };
  }, [fetchUserInfo]);

  return (
    <div className='text-3xl font-bold px-4 h-12 flex items-center justify-between relative'>
      <div className='logo flex items-center gap-2 cursor-pointer bg-white rounded-xs box-border' onClick={() => router.push(information?.website ? information?.website : ROUTE_DASHBOARD)}>
        {information?.logo ? <Image className='w-auto h-8' src={information.logo} alt='Logo' width={720} height={720} priority={true} /> : <div className='flex flex-col gap-1'><div className="skeleton h-3 w-50"></div><div className="skeleton h-3 w-50"></div></div>}
      </div>
      <div onClick={switchPopup} className='flex items-center gap-2 cursor-pointer px-2 py-1 hover:bg-[#F1F1F1] transition-all duration-300 ease-in-out select-none'>
        <div className='avanton'>{userInfo?.avatar ? <Image className='w-9 h-9 rounded-full overflow-hidden' src={userInfo.avatar} alt='Avatar' width={60} height={60} priority={true} /> : <CircleUserRound className='w-8 h-8' color="#999999"/>} </div>
        <div className='text-sm font-semibold'>{userInfo?.username || '未登录'}</div>
        <div className='text-sm font-semibold text-red-500 uppercase'>{userInfo?.roleInfo?.name || '未分配角色'}</div>
      </div>
      {isShowPopup && <div ref={popupRef} className='w-72 h-auto absolute top-14 right-2 px-2 py-4 shadow-md text-gray-700 z-20 bg-white'>
        <ul className='flex flex-col' onClick={() => setIsShowPopup(false)}>
          {popupList.map(item => (
            <React.Fragment key={item.name}>
              {
                item.method ?
                  <li onClick={item.method} className='hover:bg-[#F1F1F1] px-2 py-2 cursor-pointer text-sm text-black font-semibold flex gap-2 items-center'>
                    <Image className={`w-4.5 aspect-auto object-contain transition-all duration-300`} src={item.icon} alt={item.name} width={360} height={360} />
                    <span className='text-[#C7000B]'>{item.name}</span>
                  </li> :
                  <li className='hover:bg-[#F1F1F1] cursor-pointer text-sm text-black font-semibold'>
                    <Link target={item.isTarget ? '_blank' : '_self'} href={item.path} className='w-full py-2 px-2 font-normal  flex gap-2 items-center'>
                      <Image className={`w-4.5 aspect-auto object-contain transition-all duration-300 filter-unfocus`} src={item.icon} alt={item.name} width={360} height={360} />
                      <span className='font-medium text-gray-700'>{item.name}</span>
                    </Link>
                  </li>
              }
            </React.Fragment>
          ))}
        </ul>
      </div>}
    </div>
  )
}
